<?php
if (!(defined('IN_IA'))) 
{
    exit('Access Denied');
}

class Userinfo_MxShopModel {

    private $sessionid;
    private $userTable;
    private $userInfoTable;

    public function __construct() {
        global $_W;

        $this->userTable = tablename('mx_shop_user');
        $this->userInfoTable = tablename('mx_shop_userinfo');
    }

    /**
     * 获取会员信息
     * @param string $openid/uid 会员openid
     * @return array
     */
    public function getUser($openid = '')
    {
        global $_W;

        $info = $this->getUserInfo($openid);
        $useri = array();
        if (!empty($info)) {

            $useri = pdo_fetch(' SELECT * FROM '.$this->userTable.' WHERE id=:id', array(':id'=>$info['uid']));
            if(!empty($useri))
            {
                $credit1 = $info['credit1'];
                $credit2 = $useri['credit1'];
                $credit3 = $info['credit2'];
                $credit4 = $useri['credit2'];
                $useri['openid'] = $info['openid'];
                $useri['nickname'] = $info['nickname'];
                $useri['credit1'] = $credit1;
                $useri['credit2'] = $credit2;
                $useri['credit3'] = $credit3;
                $useri['credit4'] = $credit4;
                $useri['realname'] = empty($useri['realname']) ? $info['realname'] : $useri['realname'];
                $useri['avatar'] = empty($useri['avatar']) ? $info['avatar'] : $useri['avatar'];
                $useri['level'] = $this->getLevel($useri['levelid']);
                $useri['group'] = $this->getGroup($useri['groupid']);

                if(!strexists($useri['avatar'], 'http://') && !strexists($useri['avatar'], 'https://')){
                    $useri['avatar'] = tomedia($useri['avatar']);
                }
                if ($_W['ishttps']) {
                    $useri['avatar'] = str_replace('http://', 'https://', $useri['avatar']);
                }
            }
        }
        return $useri;
    }

    /**
     * 根据uuid获取会员信息
     * @param string $uuid 会员唯一标识
     * @param array $select 查询的字段
     * @return array
     */
    public function getUserByUuid($uuid, $select=array()){

        if(empty($uuid)){
            return null;
        }

        $info = '*';
        if(!empty($select) && is_array($select))
        {
            $info = array('id');
            foreach ($select as $item)
            {
                if(is_string($item)){
                    $info[] = $item;
                }
            }
            $info = implode(',', $info);
        }

        return pdo_fetch('SELECT '.$info.' FROM '.$this->userTable.' WHERE uuid=:uuid LIMIT 1', array(':uuid'=>$uuid));
    }

    /**
     * 根据手机号码获取会员信息
     * @param string $mobile 手机号码
     * @param array $select 查询的字段
     * @return array
     */
    public function getUserByMobile($mobile, $select=array()){

        if(empty($mobile)){
            return null;
        }

        $info = '*';
        if(!empty($select) && is_array($select))
        {
            $info = array('id');
            foreach ($select as $item)
            {
                if(is_string($item)){
                    $info[] = $item;
                }
            }
            $info = implode(',', $info);
        }

        return pdo_fetch(' SELECT '.$info.' FROM '.$this->userTable.' WHERE mobile=:mobile', array(':mobile'=>$mobile));
    }

    /*
     * 获取网关用户信息
     * @return array()
     * */
    public function getUserInfoToProxy()
    {
        global $_W;

        $params = array();
        $params['token'] = $_W['token'];
        $params['timestamp'] = TIMESTAMP;
        $params['appid'] = MX_SHOP_APPID;
        $params['sign'] = create_sign($params);

        //获取api链接
        $apiurl = proxy_url('user/info');
        //发起请求
        $res = request_post($apiurl, $params);
        //返回数组
        return $res = proxy_res_conversions($res);
    }

    /*
     * 网关登录
     * @param string $mobile 手机号码
     * @param string $pwd 未加密的密码
     * @return array()
     * */
    public function userLoginToProxy($mobile, $pwd)
    {
        global $_W;

        $params = array();
        $params['mobile'] = $mobile;
        $params['password'] = md5($pwd);
        $params['platform'] = 19491001;//$_W['uniacid'];
        $params['timestamp'] = TIMESTAMP;
        $params['appid'] = MX_SHOP_APPID;
        $params['sign'] = create_sign($params);

        //获取api链接
        $apiurl = proxy_url('user/login');
        //发起请求
        $res = request_post($apiurl, $params);
        //返回数组
        return $res = proxy_res_conversions($res);
    }

    /*
     * 网关注册
     * @param string $mobile 手机号码
     * @param string $pwd 未加密的密码
     * @param array() $params 可选参数（storeid，uuid，openid）
     * @return array()
     * */
    public function userRegisterToProxy($mobile, $pwd, $info=array())
    {
        global $_W,$_GPC;
        $params = array();
        $params['mobile'] = $mobile;
        $params['password'] = $pwd;
        $params['platform'] = 19491001;//$_W['uniacid'];
        $params['timestamp'] = TIMESTAMP;
        $params['appid'] = MX_SHOP_APPID;

        //是否门店推荐
        if(!empty($info['storeid']))
        {
            $params['storeid'] = $info['storeid'];

            //是否存在推荐人
        }elseif(!empty($info['mid']))
        {
            $params['uuid'] = $info['uuid'];
        }

        //是否存在第三方id
        if(!empty($info['openid']))
        {
            $params['openid'] = $info['openid'];
        }

        $params['sign'] = create_sign($params);

        //获取api链接
        $apiurl = proxy_url('user/register');
        //发起请求
        $res = request_post($apiurl, $params);
        //返回数组
        return proxy_res_conversions($res);
    }

    /**
     * 获取平台会员信息
     * @param string $openid/uid 会员openid
     * @return array
     */
    public function getUserInfo($openid=''){

        global  $_W;
        $uid = (int)$openid;
        if ($uid == 0) {
            $info = pdo_fetch('select * from ' . $this->userInfoTable . ' where  openid=:openid and uniacid=:uniacid limit 1', array(':uniacid' => $_W['uniacid'], ':openid' => $openid));
        } else {
            $info = pdo_fetch('select * from ' . $this->userInfoTable . ' where uid=:uid and uniacid=:uniacid limit 1', array(':uniacid' => $_W['uniacid'], ':uid' => $openid));
            if(empty($info)){
                $info['uid']=$openid;
            }
        }

        return $info;

    }

    /*
     * 注册会员信息
     * @return bool
     */
    public function checkUser(){

        global $_W;

        $member = array();
        $shopset = m('common')->getSysset(array('shop','wap'));
        $openid = $_W['openid'];

        if($_W['routes']=='order.pay_alipay' || $_W['routes']=='creditshop.log.dispatch_complete' || $_W['routes']=='threen.register.threen_complete' || $_W['routes']=='creditshop.detail.creditshop_complete' || $_W['routes']=='order.pay_alipay.recharge_complete' || $_W['routes']=='order.pay_alipay.complete' || $_W['routes']=='newmr.alipay' || $_W['routes']=='newmr.callback.gprs' || $_W['routes']=='newmr.callback.bill' || $_W['routes']=='account.sns' || $_W['plugin']=='mmanage' || $_W['routes']=='live.send.credit' || $_W['routes']=='live.send.coupon'){
            return;
        }

        if($shopset['wap']['open']){
            if($shopset['wap']['inh5app'] && is_h5app() || (empty($shopset['wap']['inh5app']) && empty($openid))){
                return;
            }
        }

        //如果你把下面这个if注释了,你就倒霉了
        if (empty($openid) && !MX_SHOP_DEBUG) {
            $diemsg = is_h5app() ? "APP正在维护, 请到公众号中访问" : "请在微信客户端打开链接";
            die("<!DOCTYPE html>
                <html>
                    <head>
                        <meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=0'>
                        <title>抱歉，出错了</title><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=0'><link rel='stylesheet' type='text/css' href='https://res.wx.qq.com/connect/zh_CN/htmledition/style/wap_err1a9853.css'>
                    </head>
                    <body>
                    <div class='page_msg'><div class='inner'><span class='msg_icon_wrp'><i class='icon80_smile'></i></span><div class='msg_content'><h4>".$diemsg."</h4></div></div></div>
                    </body>
                </html>");
        }
        $userinfo = $this->getUserInfo($openid);
        $followed = m('user')->followed($openid);
        $mc = array();
        load()->model('mc');
        if ($followed || empty($shopset['shop']['getinfo']) || $shopset['shop']['getinfo'] == 1 ) {
            if( !MX_SHOP_DEBUG ){
                $user = mc_oauth_userinfo();
            } else {
                $user = array(
                    'openid' => $userinfo['openid'],
                    'nickname' => $userinfo['nickname'],
                    'headimgurl' => $userinfo['avatar'],
                    'gender' => $userinfo['gender'],
                    'country' => $userinfo['country'],
                    'province' => $userinfo['province'],
                    'city' => $userinfo['city']
                );
            }

            $mc = array();
            $mc['nickname'] = $user['nickname'];
            $mc['avatar'] = $user['headimgurl'];
            $mc['gender'] = $user['sex'];
            $mc['country'] = $user['country'];
            $mc['resideprovince'] = $user['province'];
            $mc['residecity'] = $user['city'];
        }

        if (empty($userinfo) && !empty($openid)) {
            $userinfo = array(
                'uniacid' => $_W['uniacid'],
                'openid' => $openid,
                'realname' => !empty($mc['realname']) ? $mc['realname'] : '',
                'nickname' => !empty($mc['nickname']) ? $mc['nickname'] : '',
                'avatar' => !empty($mc['avatar']) ? $mc['avatar'] : '',
                'gender' => !empty($mc['gender']) ? $mc['gender'] : '-1',
                'country' => !empty($mc['country']) ? $mc['country'] : '',
                'province' => !empty($mc['resideprovince']) ? $mc['resideprovince'] : '',
                'city' => !empty($mc['residecity']) ? $mc['residecity'] : '',
                'area' => !empty($mc['residedist']) ? $mc['residedist'] : '',
                'createtime' => time(),
                'isuser' => 0
            );
            pdo_insert('mx_shop_userinfo', $userinfo);
            $userinfo['id'] = pdo_insertid();
        } else {
            if ($userinfo['isblack'] == 1) {
                //是黑名单
                show_message("暂时无法访问，请稍后再试!");
            }
            $upgrade = array();
            if(isset($mc['nickname']) && empty($userinfo['nickname'])){
                $upgrade['nickname'] = $mc['nickname'];
            }
            if(isset($mc['avatar']) && empty($userinfo['avatar'])){
                $upgrade['avatar'] = $mc['avatar'];
            }

            if (isset($mc['gender']) && $userinfo['gender'] != $mc['gender']) {
                $upgrade['gender'] = $mc['gender'];
            }
            if (!empty($upgrade)) {
                pdo_update('mx_shop_userinfo', $upgrade, array('id' => $userinfo['id']));
            }
        }

        return array('id'=>$userinfo['id'], 'openid'=>$userinfo['openid']);

    }

    /*
     * 通过手机号获取用户信息
     * @param string $mobile 手机号
     * @return array
     */
    public function getMobileMember($mobile) {
        global $_W;
        $info = pdo_fetch('select id from ' . $this->userTable . ' where mobile=:mobile limit 1', array(':mobile' => $mobile));
        if (!empty($info)){
            $info = $this->getUser($info['id']);
        }
        return $info;
    }

    /* 处理积分或余额
     * @param string $openid/uid 会员openid
     * @param string $credittype 处理类型
     * @param int $credit 积分或余额值
     * @param array $log 处理记录
     * @return bool
     */
    public function setCredit($openid = '', $credittype = 'credit1', $credits = 0, $log = array()) {

        global $_W;

        $user = $this->getUser($openid);
        $uid = intval($user['id']);
        if(empty($uid)){
            return false;
        }

        if (empty($log)) {
            $log = array($uid, '未记录');
        }elseif (!is_array($log)){
            $log = array(0, $log);
        }

        if($credittype=='credit1' && empty($log[0]) && $credits>0){
            // 系统充值 判断是否达到积分上限
            $shopset = m('common')->getSysset('trade');

            if(empty($user['diymaxcredit'])){
                // 系统设置
                if($shopset['maxcredit']>0){
                    if($user['credit1']>=$shopset['maxcredit']){
                        return error(-1, "用户积分已达上限");
                    }
                    elseif($user['credit1']+$credits>$shopset['maxcredit']){
                        $credits = $shopset['maxcredit'] - $user['credit1'];
                    }
                }
            }else{
                // 用户设置
                if($user['maxcredit']>0){
                    if($user['credit1']>=$user['maxcredit']){
                        return error(-1, "用户积分已达上限");
                    }
                    elseif($user['credit1']+$credits>$user['maxcredit']){
                        $credits = $user['maxcredit'] - $user['credit1'];
                    }
                }
            }
        }

        $log_data = array(
            'uid' => intval($uid),
            'credittype' => $credittype,
            'uniacid' => $_W['uniacid'],
            'num' => $credits,
            'createtime' => TIMESTAMP,
            'module' => 'mx_shop',
            'operator' => intval($log[0]),
            'remark' => $log[1],
        );

        //平台积分
        if($credittype == 'credit1'){
            $newcredit = $credits + $user['credit1'];
            if ($newcredit <= 0) {
                $newcredit = 0;
            }

            pdo_update('mx_shop_userinfo', array('credit1' => $newcredit), array('uid' => $uid, 'uniacid'=>$_W['uniacid']));

        //通用积分
        }elseif($credittype == 'credit2'){
            $newcredit = $credits + $user['credit2'];
            if ($newcredit <= 0) {
                $newcredit = 0;
            }
            $res = pdo_update('mx_shop_user', array('credit1' => $newcredit), array('id' => $uid));

        //平台余额
        }elseif($credittype == 'credit3'){
            $newcredit = $credits + $user['credit3'];
            if ($newcredit <= 0) {
                $newcredit = 0;
            }
            pdo_update('mx_shop_userinfo', array('credit2' => $newcredit), array('uid' => $uid, 'uniacid'=>$_W['uniacid']));

        //通用余额
        }elseif($credittype == 'credit4'){
            $newcredit = $credits + $user['credit4'];
            if ($newcredit <= 0) {
                $newcredit = 0;
            }
            pdo_update('mx_shop_user', array('credit2' => $newcredit), array('id' => $uid));
        }

        pdo_insert('mc_credits_record', $log_data);

        return true;
    }

    /* 获取积分或余额
     * @param srting $openid 会员openid
     * @param string $credittype 获取的类型
     * @return false/value
     */
    public function getCredit($openid = '', $credittype = 'credit1') {

        global $_W;

        $user = $this->getUser($openid);

        if(empty($user)){
            return false;
        }

        if(!in_array($credittype, array('credit1', 'credit2', 'credit3', 'credit4'))){
            return false;
        }

        return $user[$credittype];

    }

    /* 获取积分或余额
     * @param string $openid 会员openid
     * @param array $credittypes 获取所有的类型
     * @return bool/value
     */
    public function getCredits($openid = '', $credittypes = array('credit1', 'credit2', 'credit3', 'credit4')) {

        global $_W;
        $user = $this->getUser($openid);
        if(empty($user)){
            return false;
        }

        $types = array('credit1'=>0, 'credit2'=>0, 'credit3'=>0, 'credit4'=>0);
        if(is_array($credittypes)){
            foreach ($credittypes as $credittype) {
                if(!in_array($credittype, array('credit1', 'credit2', 'credit3', 'credit4'))){
                    $types[$credittype] = $user[$credittype];
                }
            }
        }

        return $types;
    }

    /**
     * 获取所有会员等级
     * @param bool $all 是否启用
     * @return array
     */
    function getLevels($all=true) {
        global $_W;

        $condition = '';
        if($all){
            $condition = " and status=1";
        }
        return pdo_fetchall('select * from ' . tablename('mx_shop_user_level') . ' where uniacid=:uniacid'.$condition.' order by level asc', array(':uniacid' => $_W['uniacid']));
    }

    /* 获取会员等级
     * @param string $openid 会员openid
     * @return array 会员等级信息
     */
    function getLevel($id) {
        global $_W, $_S;
        if (empty($id)) {
            return false;
        }
        $level = pdo_fetchcolumn('select levelname from ' . tablename('mx_shop_user_level') . ' where id=:id and uniacid=:uniacid and status=1 limit 1', array(':id' => $id, ':uniacid' => $_W['uniacid']));
        if (!empty($level)) {
            return $level;
        }

        return empty($_S['shop']['levelname']) ? '普通会员' : $_S['shop']['levelname'];
    }

    /**
     * 获取所有会员组
     * @return array
     */
    function getGroups() {
        global $_W;

        return pdo_fetchall('select * from ' . tablename('mx_shop_user_group') . ' where uniacid=:uniacid ', array(':uniacid' => $_W['uniacid']));
    }

    /* 获取会员组
     * @param string $id 会员levelid
     * @return array 会员等级信息
     */
    function getGroup($id) {
        global $_W;
        if (empty($id)) {
            return false;
        }

        $group = pdo_fetchcolumn('select groupname from ' . tablename('mx_shop_user_group') . ' where id=:id and uniacid=:uniacid limit 1', array(':id' => $id, ':uniacid' => $_W['uniacid']));
        if (!empty($group)) {
            return $group;
        }

        return false;
    }

}
